package com.qd.p2p.web.action.additional;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;

import com.alibaba.fastjson.JSON;
import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.service.FinanFlowQueryService;
import com.qdlc.p2p.biz.service.FinanFlowService;
import com.qdlc.p2p.biz.tpp.TppBaseInterface;
import com.qdlc.p2p.biz.tpp.TppServiceFactory;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.Constant;
import com.qdlc.p2p.common.exception.FinanFlowExecption;
import com.qdlc.p2p.common.util.Base64Util;
import com.qdlc.p2p.common.util.BigDecimalUtil;
import com.qdlc.p2p.common.util.MessageUtil;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dto.AdditionalFlowInvestor;
import com.qdlc.p2p.dal.dto.AdditionalFlowProject;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.FlowInvestorModel;
import com.qdlc.p2p.dal.model.FlowProjectModel;
import com.qdlc.p2p.dal.model.FlowYieldPlanModel;
import com.qdlc.p2p.dal.model.TppModel;
import com.qdlc.p2p.dal.util.UserUtils;

/**
 * 理财功能投标查询
 * @author wjx
 * @version 2.0
 * @date 2015年5月16日 下午4:08:03
 */
public class AdditionalFlowAction extends BaseAction<FlowProjectModel> implements
ModelDriven<FlowProjectModel> {
	
	
	@Resource
	private FinanFlowService finanFlowService;
	
	@Resource
	private FinanFlowQueryService finanFlowQueryService;
	
	private Map<String, Object> data;
	
	/**
	 * 获取json数据
	 * @throws IOException
	 */
	@Action(value = "/additional/flow/projectTenderJson", interceptorRefs = {
			@InterceptorRef("session"), @InterceptorRef("globalStack") })
	public void projectTenderJson() throws IOException{
		data = new HashMap<String, Object>();
		PageDataList<FlowInvestorModel> list = finanFlowQueryService.getInvestorList(model.getId(), model.getPage(), 0);
		data.put("data", list);
		printWebJson(getStringOfJpaObj(data));
	}
	
	/**
	 * 购买理财项目
	 * @return
	 * @throws Exception 
	 */
	@Action(value = "/additional/flow/buyFlowProject" ,results = {
			@Result(name = "result", type = "ftl", location = "/member/tpp/" + Constant.TPP_PACKAGE + "/tender.html") },
				interceptorRefs = { @InterceptorRef("session"), @InterceptorRef("globalStack") })
	public String buyFlowProject() throws Exception{
		checkToken("flowtenderToken");
		int tCopies = model.getYesCopies();
		User user = this.getSessionUser();
		AdditionalFlowProject flowProject = finanFlowService.getFlowProjectByUuid(model.getUuid());
		if (tCopies<1) {
			throw new FinanFlowExecption(MessageUtil.getMessage("MF103004003"));
		}
		
		if (user.getUserId() == flowProject.getUser().getUserId()) {
			throw new FinanFlowExecption(MessageUtil.getMessage("MF103004004"));
		}
		
		int surplusCount = flowProject.getTotalCopies() -flowProject.getYesCopies(); //计算剩余份数
		if (surplusCount<=flowProject.getStartCopies()) {
			//校验购买份数是否等于剩余份数
			if (tCopies !=surplusCount) {
				throw new FinanFlowExecption(MessageUtil.getMessage("MF103002009"));
			}
		}else{
			//校验购买份数是否小于起投份数
			if (tCopies<flowProject.getStartCopies()) {
				throw new FinanFlowExecption(MessageUtil.getMessage("MF103002010"));
			}
		}
		//校验购买份数是否超出剩余可买份数
		if (tCopies > surplusCount) {
			throw new FinanFlowExecption(MessageUtil.getMessage("MF103002001"));
		}
		
		AdditionalFlowInvestor investor = new AdditionalFlowInvestor();
		investor.setUser(user);
		//计算投资金额
		double tenderMoney = BigDecimalUtil.mul(tCopies,flowProject.getEachMoney());
		investor.setBuyMoney(tenderMoney);
		model.setStatus(flowProject.getStatus());
		model.checkTender(investor);
		model.checkTenderPwd(user);
		TppModel tppModel = new TppModel();
		tppModel.setUser(user);
		tppModel.setTppUserCustId(UserUtils.getUserTppCustId(user.getUserId()));
		tppModel.setToTppUserCustId(UserUtils.getUserTppCustId(flowProject.getUser().getUserId()));
		tppModel.setMoney(tenderMoney);
		tppModel.setTppBorrowId("F_"+flowProject.getId());
		tppModel.setBorrowAccount(flowProject.getAccount());
		// 封装用户扩展参数
		data = new HashMap<String, Object>();
		data.put("tenderCopies",tCopies);
		data.put("uuid", flowProject.getUuid());
		tppModel.setExtended(Base64Util.base64Encode(JSON.toJSONString(data)));
		tppModel.setIsFlow(1);
		// 获取第三方托管方式
		TppBaseInterface tppService = TppServiceFactory.newIntance();
		Object tender = tppService.tppAddFlowTender(tppModel);
		request.setAttribute("tender", tender);
		return "result";
	}
	
	
	/**
	 * 个人中心购买流转标列表
	 * @return
	 * @throws IOException 
	 */
	@Action(value = "/member/invest/myTenderFlow" ,results = { @Result(name = "index", type = "ftl", location = "/borrow/index.html")},
			interceptorRefs = { @InterceptorRef("session"), @InterceptorRef("globalStack") })
	public String myTenderFlow() throws IOException{
		checkInvestUser();
		return "myTenderFlow";
	}
	
	@Action(value = "/member/invest/myTenderFlowJson" ,results = { @Result(name = "index", type = "ftl", location = "/borrow/index.html")},
			interceptorRefs = { @InterceptorRef("session"), @InterceptorRef("globalStack") })
	public void myTenderFlowJson() throws IOException{
		User user = this.getSessionUser();
		PageDataList<FlowInvestorModel> list = finanFlowQueryService.getUserInvestList(user.getUserId(), model);
		data = new HashMap<String, Object>();
		data.put("data", list);
		printWebJson(getStringOfJpaObj(data));
	}
	
	@Action(value = "/member/invest/myYieldPlanJson" ,results = { @Result(name = "index", type = "ftl", location = "/borrow/index.html")},
			interceptorRefs = { @InterceptorRef("session"), @InterceptorRef("globalStack") })
	public void myYieldPlanJson() throws IOException{
		User user = this.getSessionUser();
		PageDataList<FlowYieldPlanModel> pageList = finanFlowQueryService.getUserYieldPlan(user.getUserId(), model);
		data = new HashMap<String, Object>();
		data.put("data", pageList);
		printWebJson(getStringOfJpaObj(data));
	}
	
}
